package com.yutel.comp.queue.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.yutel.comp.queue.QueueConfig;
import com.yutel.comp.queue.QueueLog;
import com.yutel.comp.queue.QueueProducer;

public class JmsProducer implements QueueProducer {
	protected static QueueLog log = QueueLog.getLogger(JmsProducer.class);
	private QueueConfig.Producer config;
	private Connection connection = null;
	private Session session = null;
	private MessageProducer producer = null;

	public JmsProducer() {
		config = QueueConfig.getProducer();
	}

	@Override
	public boolean send(String msg) {
		try {
			if (log.isDebugEnabled()) {
				log.debug("txt=" + msg);
			}
			TextMessage message = session.createTextMessage(msg);
			producer.send(message);
			return true;
		} catch (JMSException e) {
			log.error("send fail,repeat connection", e);
			close();
			conn();
			return false;
		} catch (Exception e) {
			log.error("send fail:", e);
			return false;
		}
	}

	public synchronized void conn() {
		log.info("get producer connection");
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD,
				config.ServiceUrl + "?wireFormat.maxInactivityDuration=0");
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(Boolean.FALSE,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(
					config.QueueName + "?consumer.prefetchSize=10");
			producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
		} catch (Exception e) {
			log.error("get producer connect error", e);
		}
	}

	public synchronized void close() {
		try {
			if (producer != null) {
				producer.close();
			}
			if (session != null) {
				session.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			log.error("close connect error", e);
		}
	}

	@Override
	public void start() {
		conn();
	}

}
